package com.atung.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.atung.model.WxLoginDTO;
import com.atung.request.RequestWxLogin;
import com.atung.request.RequestWxRegister;
import com.atung.response.ResponseChangeSchool;
import com.atung.response.ResponseWxLogin;
import com.atung.service.UserLoginService;
import com.atung.tool.WXBizDataCrypt;
import com.atung.tool.wxUrl.WxUrlTool;
import com.yuyi.full.Result;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/wx")
@Api(tags="微信认证接口")
public class UserLoginController {

	@Autowired
	private UserLoginService userLoginService;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    
    
	@PostMapping("/login")
	@ApiOperation("用户登录")
	public Result<ResponseWxLogin> userLogin(@Valid @RequestBody RequestWxLogin request) throws Exception{
//		String url=String.format(WxUrlTool.GetWxLoginUrl,appid,secret,request.getCode());
		String url=(WxUrlTool.GetWxLoginUrl.replace("APPID", appid).replace("SECTET", secret).replace("JSCODE", request.getCode()));
		String response=HttpUtil.get(url);

		WxLoginDTO  loginMessage=JSONUtil.toBean(response, WxLoginDTO.class);
		if(Objects.nonNull(loginMessage.getErrcode())){
			return Result.error(loginMessage.getErrcode(),loginMessage.getErrmsg());
		}
		loginMessage.setOpenid(loginMessage.getOpenid());
		ResponseWxLogin wxLogin=userLoginService.selectUserAndOpenId(loginMessage);
		wxLogin.setSession_key(loginMessage.getSession_key());
		return Result.success(wxLogin);
	}
	
	
	@PostMapping("/perfect")
	@ApiOperation("完善信息")
	public Result userPerfect(@RequestBody @Valid RequestWxRegister request){
		userLoginService.updatetUserAndOpenId(request);
		return Result.success();
	}
	
	@GetMapping("/nearbySchool")
	@ApiOperation("根据当前位置推荐附近学校")
	public Result<List<ResponseChangeSchool>>nearbySchool(@RequestParam String lon,@RequestParam String lat){
		return Result.success(userLoginService.selectSchoolBylonAndlat(lon, lat));
		}
	
	/**
    * 小程序授权获取手机号
    */
   @GetMapping(value="/getPhoneNumber")
   @ApiOperation("获取手机号")
   public  Result getPhoneNumber(String encryptedData, String iv, String session_key) {
       Map<String,Object> map=new HashMap<>();
       
       String result=WXBizDataCrypt.decrypt1(encryptedData,session_key,iv);
       JSONObject json=JSONObject.parseObject(result);
       
       if (!Objects.isNull(result)&&result.length()>0) {
       	map.put("purePhoneNumber", json.getString("purePhoneNumber"));
       	map.put("phoneNumber", json.getString("phoneNumber"));
       	map.put("countryCode", json.getString("countryCode"));
       	map.put("msg","success");
       }
       map.put("msg","error");
       return Result.success(map);
   }
}
